package com.ktg.common.core.domain;

import com.alibaba.fastjson.JSONObject;
import com.ktg.common.constant.HttpStatus;
import com.ktg.common.core.domain.model.SqlResult;
import com.ktg.common.utils.spring.SpringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.swing.table.TableColumn;
import java.util.Date;
import java.util.List;

public class APIResult<T>  {

    private static boolean allLog = isLog();
    private boolean allResutl = true;
    private static final Logger log = LoggerFactory.getLogger(Result.class);
    private Date startTime = null;
    private long useTime = 0;
    private String msg = null;



    public APIResult(String apiDes,HttpServletRequest req,T object){
        startTime = new Date();
        msg = "\n:名称："+apiDes;
        msg +="\n:时间："+ com.ktg.common.utils.DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss",startTime);
        if(req != null){
            String queryString = req.getQueryString();
            msg +="\n:接口："+req.getRequestURI() +"";
            if (queryString != null){
                msg += "\n:参数1："+queryString;
            }
        }
        if (object != null){
            try {
                String js = JSONObject.toJSONString(object);
                msg += "\n:参数2："+js;
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    public APIResult(HttpServletRequest req,T object){
        startTime = new Date();
        msg = "\n:时间："+ com.ktg.common.utils.DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss",startTime);
        if(req != null){
            String queryString = req.getQueryString();
            msg = "\n:接口："+req.getRequestURI()+"";
            if (queryString != null){
                msg += "\n:参数1："+queryString;
            }
        }
        if (object != null){
            try {
                String js = JSONObject.toJSONString(object);
                msg += "\n:参数2："+js;
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    public Result<T> ok(T result){
       return ok(result,null);
    }

    public  Result sqlResult(SqlResult sqlResult){
        if (sqlResult.isSuccess()){
            String msg = sqlResult.getMsg() == null? "操作成功": sqlResult.getMsg();
            return ok(msg,sqlResult.getData(),null);
        }else {
            String msg = sqlResult.getMsg() == null? "操作失败": sqlResult.getMsg();
            return fail(msg,sqlResult.getData());
        }
    }
    public Result<T> ok(T result, List<TableColumn> columns){
        return ok("操作成功",result,columns);
    }


    public Result ok(String message,Object result, List<TableColumn> columns){
        new  Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    boolean isLog = allLog;
                    if (startTime.before(DateUtils.addSeconds(new Date(),-5))){
                        isLog = true;
                        useTime = System.currentTimeMillis() - startTime.getTime();
                    }
                    msg += "\n:耗时："+useTime;
                    msg += "\n:code:"+ HttpStatus.SUCCESS;
                    if (allResutl){
                        try {
                            String js = JSONObject.toJSONString(result);
                            msg += "\n:result："+js;
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                    if (isLog){
                        APIResult.printResponse(msg);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();

        return Result.OK(message,result,columns);
    }
    public Result<T> fail(String msgStr){
        return fail(msgStr,null);
    }

    public Result fail(String msgStr,Object object){
        boolean isLog = allLog;
        int code = 2001;
        if (startTime.before(DateUtils.addSeconds(new Date(),-5))){
            isLog = true;
            useTime = System.currentTimeMillis() - startTime.getTime();
        }
        msg += "\n:耗时："+useTime;
        msg += "\n:code:"+ code;
        if (allResutl){
            msg += "\n:result："+msgStr;
        }
        if (isLog){
            log.error(msg);
        }
        return Result.ERROR(code,msgStr,object);
    }

    public Result<T> error(Exception e){
        boolean isLog = true;
        int code = 2002;
        useTime = System.currentTimeMillis() - startTime.getTime();
        msg += "\n:耗时："+useTime;
        msg += "\n:code:"+ code;
        if (allResutl && e != null){
            msg += "\n:result："+e.getLocalizedMessage();
        }
        if (isLog){
            e.printStackTrace();
            log.error(msg,e.getStackTrace().toString());
        }
        Throwable cause = e.getCause();
        if(cause != null){
            String message = cause.getMessage();
            JSONObject msgObj = (JSONObject) JSONObject.parse(message);
            if(msgObj.get("message")!=null){
                return Result.ERROR(code,(String)msgObj.get("message"));
            }
        }
        return Result.ERROR(code,"操作异常");
    }


    //打印日志
    public static void printRequest(HttpServletRequest request,String token){
        if(isLog()){
            String requestURI = request.getRequestURI();
            try{
                log.debug(SpringUtils.getActiveProfile()+": 接口 = "+requestURI+"\n token:"+token);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    public static boolean isLog(){
        String active = SpringUtils.getActiveProfile();
        if(active.equals("dev")){
            return true;
        }
        return false;
    }

    //打印日志
    public static void printResponse(String response){
        if(allLog){
            try{
                String method = Thread.currentThread().getStackTrace()[3].getMethodName();
                String className = Thread.currentThread().getStackTrace()[3].getClassName();
                log.debug(SpringUtils.getActiveProfile()+": 返回 ="+className+"."+ method+" \n "+response);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }


}
